
/**		
 * 
 *	uk.co.lmfm.guppy.controller.SetUserSettingsCommand
 *	
 *	@version 1.00 | Jan 12, 2010
 *	@author Justin Windle
 *  
 **/
 
package uk.co.lmfm.guppy.controller 
{
	import uk.co.lmfm.guppy.model.LibraryProxy;

	import org.osflash.thunderbolt.Logger;

	import uk.co.lmfm.guppy.application.enum.ApplicationConstants;
	import uk.co.lmfm.guppy.model.SettingsProxy;
	import uk.co.lmfm.guppy.model.SVNProxy;
	import uk.co.lmfm.guppy.model.vo.SettingsVO;
	import uk.co.lmfm.guppy.model.vo.ValidatedSettingsVO;

	import org.puremvc.as3.multicore.interfaces.ICommand;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.command.SimpleCommand;

	/**
	 * SetUserSettingsCommand
	 */
	public class SetUserSettingsCommand extends SimpleCommand implements ICommand 
	{
		override public function execute(notification : INotification) : void
		{
			super.execute(notification);
			
			var sqlProxy : SettingsProxy = facade.retrieveProxy(SettingsProxy.NAME) as SettingsProxy;
			var libProxy : LibraryProxy = facade.retrieveProxy(LibraryProxy.NAME) as LibraryProxy;			var svnProxy : SVNProxy = facade.retrieveProxy(SVNProxy.NAME) as SVNProxy;
			
			var newSettings : SettingsVO = notification.getBody() as SettingsVO;			var oldSettings : SettingsVO = sqlProxy.readSettings();
			
			var validation : ValidatedSettingsVO = sqlProxy.validateSettings(newSettings);
			
			if(validation.valid)
			{
				sqlProxy.writeSettings(newSettings);
				libProxy.setLibraryPath(newSettings.libraryPath);
				libProxy.configureLibrary(newSettings);
				
				if(newSettings.libraryPath != oldSettings.libraryPath)
				{
					svnProxy.checkForUpdates();
					// TODO copy library from old to new location
				}
				
				sendNotification(ApplicationConstants.SET_USER_SETTINGS_SUCCESS, newSettings);
				sendNotification(ApplicationConstants.SET_LIBRARY_PATH);
				sendNotification(ApplicationConstants.ENABLE_MENU);
			}
			else
			{
				Logger.error("Failed to set user preferences. A field is invalid: " + validation.results);
				
				sendNotification(ApplicationConstants.SET_USER_SETTINGS_FAILED, validation);
			}
		}
	}
}
